package com.zhongan.hystrix.demo;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;

import rx.Observable;
import rx.Observer;
import rx.functions.Action1;

public class CommandHelloWorld extends HystrixCommand<String> {

	private String name;

	public CommandHelloWorld(String name) {
		super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
		this.name = name;
	}

	@Override
	protected String run() throws Exception {
		// TODO Auto-generated method stub
		return "Hello " + name + "!";
	}

	public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
		// 同步调用
		String result = new CommandHelloWorld("Kaic").execute();
		System.out.println("result = " + result);
		// 异步调用
		// 同步调用command.execute()等价于command.queue().get()
		Future<String> futures = new CommandHelloWorld("kaic").queue();
		result = futures.get(100, TimeUnit.MILLISECONDS);
		System.out.println("result2 = " + result);
		// 注册异步事件回调执行
		Observable<String> obs = new CommandHelloWorld("Kaic").observe();
		// command.observer().toBlocking().toFuture().get()等价于command.queue().get()
		result = obs.toBlocking().toFuture().get();
		System.out.println("result3 = " + result);
		// 注册观察者事件拦截
		obs.subscribe(new Action1<String>() {
			public void call(String arg0) {
				System.out.println("result4 = " + arg0);
			}
		});
		// 注册完整执行生命周期事件
		obs.subscribe(new Observer<String>() {

			public void onCompleted() {
				// onNext/onError完成之后最后回调  
				System.out.println("execute onCompleted");
			}

			public void onError(Throwable e) {
				// 当产生异常时回调  
				System.out.println("onError " + e.getMessage());
				e.printStackTrace();
			}

			public void onNext(String v) {
				// 获取结果后回调  
				System.out.println("onNext: " + v);
			}

		});
	}

}
